package com.paas.form.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.util.UniqueIdUtil;
import com.paas.common.web.service.BaseServiceImpl;
import com.paas.form.constant.FormConstant;
import com.paas.form.dao.FormViewDao;
import com.paas.form.entity.*;
import com.paas.form.service.*;
import com.paas.form.vo.ViewFinalizeVo;
import com.publics.feign.service.IUcDataBaseService;

@Service("formViewService")
public class FormViewServiceImpl extends BaseServiceImpl<FormViewDao, FormViewEntity> implements IFormViewService {

    @Autowired
    public IFormAttributeService formAttributeService;

    @Autowired
    public IFormViewPubService formViewPubService;

    @Autowired
    public IFormAttributePubService formAttributePubService;

    @Autowired
    public IUcDataBaseService ucDataBaseService;

    @Autowired
    public IFormViewFinalVersionService formViewFinalVersionService;

    @Autowired
    public IFormGroupService formGroupService;
    @Autowired
    public IFormGroupFinalService formGroupFinalService;

    /**
     * 审批发布审批页面显示对象
     * 
     * @param
     * @return
     */
    @Override
    public ViewFinalizeVo getViewFinalizeById(String viewFinalVesionId) {

        FormViewFinalVersionEntity formViewFinalVersionBean = formViewFinalVersionService.getById(viewFinalVesionId);
        if (BeanUtil.isEmpty(formViewFinalVersionBean)) {
            return null;
        }
        String viewId = formViewFinalVersionBean.getViewId();
        // 根据id查询视图
        FormViewEntity formViewEntity = this.getById(viewId);
        if (BeanUtil.isEmpty(formViewEntity)) {
            return null;
        }

        // 定义返回对象
        ViewFinalizeVo viewFinalizeVo = new ViewFinalizeVo();
        // 查询数据源
        DataBaseEntity dataBaseEntity = ucDataBaseService.queryById(formViewEntity.getDatasource());
        viewFinalizeVo.setDatasourceName(dataBaseEntity.getJdbcName());
        BeanUtil.copyProperties(viewFinalizeVo, formViewEntity);
        if (StringUtil.isNotEmpty(formViewFinalVersionBean.getNewViewName())) {
            viewFinalizeVo.setName(formViewFinalVersionBean.getNewViewName());
        }
        // 查询视图属性信息
        List<FormAttributeEntity> formAttributeEntityList = formAttributeService.getListByViewId(viewId);
        viewFinalizeVo.setAttributes(formAttributeEntityList);// 填充主视图属性
        // 查询子视图信息
        List<FormViewEntity> childrenViewList = this.getChildViewByViewId(viewId);
        if (BeanUtil.isNotEmpty(childrenViewList)) {
            // 子视图id集合
            List<String> childrenViewIds = childrenViewList.stream().map(FormViewEntity::getId).collect(Collectors.toList());
            Map<String, List<FormAttributeEntity>> childrenAttributeMap = new HashMap<String, List<FormAttributeEntity>>();
            // 根据视图id集合查询属性
            List<FormAttributeEntity> childrenAttributeList = formAttributeService.getListByViewIds(childrenViewIds);
            if (BeanUtil.isNotEmpty(childrenAttributeList)) {
                childrenAttributeMap = childrenAttributeList.stream().collect(Collectors.groupingBy(FormAttributeEntity::getViewId));
            }
            // 子视图定义对象
            List<ViewFinalizeVo> childrenList = new ArrayList<ViewFinalizeVo>();
            // 设置子视图信息
            ViewFinalizeVo children = null;
            for (FormViewEntity temp : childrenViewList) {
                children = new ViewFinalizeVo();
                BeanUtil.copyProperties(children, temp);
                if (childrenAttributeMap != null && childrenAttributeMap.containsKey(temp.getId())) {
                    children.setAttributes(childrenAttributeMap.get(temp.getId()));
                }
                childrenList.add(children);
            }
            viewFinalizeVo.setChildrenList(childrenList);
        }
        return viewFinalizeVo;
    }

    /**
     * 视图发布反对
     * 
     * @param
     * @return
     */
    @Override
    public RestResponse opposeViewFinalize(String viewFinalVesionId) {

        FormViewFinalVersionEntity formViewFinalVersionBean = formViewFinalVersionService.getById(viewFinalVesionId);
        if (BeanUtil.isEmpty(formViewFinalVersionBean)) {
            return RestResponse.error("[" + viewFinalVesionId + "]找不到关联的数据，请检查请求参数");
        }
        String viewId = formViewFinalVersionBean.getViewId();

        FormViewEntity formViewEntity = this.getById(viewId);
        if (BeanUtil.isEmpty(formViewEntity)) {
            return RestResponse.error("[" + viewId + "]找不到关联的视图数据，请检查请求参数");
        }
        if (!FormConstant.CHANGE_OPERATION_APPROVAL.equals(formViewEntity.getBizStatus())) {
            return RestResponse.error("[" + viewId + "]只有审批中的数据，才允许执行反对操作");
        }
        formViewEntity.setBizStatus(FormConstant.CHANGE_OPERATION_APPROVAL); // 回滚至暂存状态
        this.updateById(formViewEntity);
        return RestResponse.success("数据更新成功");
    }

    @Override
    public RestResponse approvalViewChange(String viewFinalVesionId) {

        FormViewFinalVersionEntity formViewFinalVersionBean = formViewFinalVersionService.getById(viewFinalVesionId);
        if (BeanUtil.isEmpty(formViewFinalVersionBean)) {
            return RestResponse.error("[" + viewFinalVesionId + "]找不到关联的数据，请检查请求参数");
        }
        String viewId = formViewFinalVersionBean.getViewId();

        FormViewEntity formViewEntity = this.getById(viewId);
        if (BeanUtil.isEmpty(formViewEntity)) {
            return RestResponse.error("[" + viewId + "]找不到关联的视图数据，请检查请求参数");
        }
        if (!FormConstant.CHANGE_OPERATION_APPROVAL.equals(formViewEntity.getBizStatus())) {
            return RestResponse.error("[" + viewId + "]只有审批中的数据，才允许执行通过操作");
        }
        // 定义定版视图新增对象集合
        List<FormViewPubEntity> addFormViewPubList = new ArrayList<FormViewPubEntity>();
        // 定义定版视图新增属性对象集合
        List<FormAttributePubEntity> addFormAttributePubList = new ArrayList<FormAttributePubEntity>();
        // 查询视图属性信息
        List<FormAttributeEntity> formAttributeEntityList = formAttributeService.getListByViewId(viewId);
        // 定义主视图定版对象
        FormViewPubEntity rootViewPubEntity = new FormViewPubEntity();
        BeanUtil.copyProperties(rootViewPubEntity, formViewEntity); // 拷贝属性
        rootViewPubEntity.setId(UniqueIdUtil.getGuid());
        rootViewPubEntity.setCreateDate(new Date());
        if (StringUtil.isNotEmpty(formViewFinalVersionBean.getNewViewName())) {
            rootViewPubEntity.setName(formViewFinalVersionBean.getNewViewName());
        }
        // 定义属性新增对象
        FormAttributePubEntity addFormAttributePubEntity = null;
        // 设置主视图属性
        if (BeanUtil.isNotEmpty(formAttributeEntityList)) {
            for (FormAttributeEntity formAttributeEntity : formAttributeEntityList) {
                addFormAttributePubEntity = new FormAttributePubEntity();
                BeanUtil.copyProperties(addFormAttributePubEntity, formAttributeEntity); // 拷贝属性
                addFormAttributePubEntity.setCreateDate(new Date());
                addFormAttributePubEntity.setId(UniqueIdUtil.getGuid());
                addFormAttributePubEntity.setViewId(rootViewPubEntity.getId());// 关联id更新
                addFormAttributePubList.add(addFormAttributePubEntity);
            }
        }
        // 查询子视图信息
        List<FormViewEntity> childrenViewList = this.getChildViewByViewId(viewId);
        // 非空判断
        if (BeanUtil.isNotEmpty(childrenViewList)) {
            // 子视图id集合
            List<String> childrenViewIds = childrenViewList.stream().map(FormViewEntity::getId).collect(Collectors.toList());
            Map<String, List<FormAttributeEntity>> childrenAttributeMap = new HashMap<String, List<FormAttributeEntity>>();
            // 根据视图id集合查询属性
            List<FormAttributeEntity> childrenAttributeList = formAttributeService.getListByViewIds(childrenViewIds);
            if (BeanUtil.isNotEmpty(childrenAttributeList)) {
                childrenAttributeMap = childrenAttributeList.stream().collect(Collectors.groupingBy(FormAttributeEntity::getViewId));
            }
            // 定版视图对象
            FormViewPubEntity addFormViewPubEntity = null;
            // 子视图添加至定版视图
            for (FormViewEntity temp : childrenViewList) {
                addFormViewPubEntity = new FormViewPubEntity();
                BeanUtil.copyProperties(addFormViewPubEntity, temp);
                addFormViewPubEntity.setCreateDate(new Date());
                addFormViewPubEntity.setId(UniqueIdUtil.getGuid()); // 主键重新生成
                addFormViewPubEntity.setViewId(rootViewPubEntity.getId());// 主视图id重新设置
                if (childrenAttributeMap != null && childrenAttributeMap.containsKey(temp.getId())) {
                    // 子视图属性
                    List<FormAttributeEntity> childViewAttributeEntityList = childrenAttributeMap.get(temp.getId());
                    // 遍历设置子视图属性
                    for (FormAttributeEntity formAttributeEntity : childViewAttributeEntityList) {
                        addFormAttributePubEntity = new FormAttributePubEntity();
                        BeanUtil.copyProperties(addFormAttributePubEntity, formAttributeEntity); // 拷贝属性
                        addFormAttributePubEntity.setCreateDate(new Date());
                        addFormAttributePubEntity.setId(UniqueIdUtil.getGuid());
                        addFormAttributePubEntity.setViewId(addFormViewPubEntity.getId());// 关联视图id更新
                        addFormAttributePubList.add(addFormAttributePubEntity); // 添加数据至集合
                    }
                }
                addFormViewPubList.add(addFormViewPubEntity);
            }
        }
        addFormViewPubList.add(rootViewPubEntity); // 添加主视图至集合

        String groupId = formViewEntity.getGroupId();
        // 判断定版分组是否存在，不存在则新增
        if (StringUtil.isNotEmpty(groupId)) {
            FormGroupFinalEntity groupFinalEntity = formGroupFinalService.getById(groupId);
            if (BeanUtil.isEmpty(groupFinalEntity)) {
                FormGroupEntity formGroup = formGroupService.getById(groupId);
                groupFinalEntity = new FormGroupFinalEntity();
                BeanUtil.copyProperties(groupFinalEntity, formGroup);
                formGroupFinalService.save(groupFinalEntity);
            }
        }
        // 添加定版视图
        formViewPubService.insertBatch(addFormViewPubList);
        // 定版视图属性存储
        if (addFormAttributePubList.size() > 0) {
            formAttributePubService.insertBatch(addFormAttributePubList);
        }
        formViewEntity.setBizStatus(FormConstant.CHANGE_OPERATION_SUCCESS); // 视图表状态更新
        this.updateById(formViewEntity);
        return RestResponse.success("数据更新成功");
    }

    /**
     * 根据主视图查询子视图信息
     * 
     * @param viewId
     * @return
     */
    @Override
    public List<FormViewEntity> getChildViewByViewId(String viewId) {
        QueryWrapper<FormViewEntity> queryWrapper = new QueryWrapper<FormViewEntity>();
        queryWrapper.eq("view_id", viewId);
        return this.baseMapper.selectList(queryWrapper);
    }

}